package com.wk.arth.str;

public class BF {
	// 字串needle在主串haystack中首次出现位置
	public int strStr(String haystack,String needle) {
		int haylen = haystack.length();
		int needlen = needle.length();
		if(haylen<needlen) {
			return -1;
		}
		if(needlen == 0) {
			return 0;
		}
		for (int i = 0; i < haylen-needlen+1; i++) {
			int j;
			for (j = 0; j<needlen; j++) {
				if(haystack.charAt(i+j)!=needle.charAt(j)) {
					break;
				}
			}
			if(j == needlen) {
				return i;
			}
		}
		return -1;
	}
	
	public int strStr2(String haystack,String needle) {
		int haylen = haystack.length();
		int needlen = needle.length();
		if(haylen<needlen) {
			return -1;
		}
		if(needlen == 0) {
			return 0;
		}
		int i,j;
		for(i=0,j=0;i<haylen&&j<needlen;i++) {
			if(haystack.charAt(i) == needle.charAt(j)) {
				j++;
			}else {
				i-=j;
				j=0;
			}
		}
		
		return j==needlen?i-j:-1;
	}
	
	public static void main(String[] args) {
		BF bf = new BF();
		System.out.println(bf.strStr("ssdnbs", "sdn"));
		System.out.println(bf.strStr2("ssdnbs", "sdn"));
	}
}
